package activity

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/activity"
	"gq_volunteer_platform/model/admin"
	ServiceAdmin "gq_volunteer_platform/service/admin"
	"time"

	"gq_volunteer_platform/service/message_queue"

	"github.com/lluck42/tools"

	"github.com/gin-gonic/gin"
)

func MyList(c *gin.Context) {

	var req struct {
		Page           int    `binding:"required,gte=1"`
		Limit          int    `binding:"required,gte=1"`
		ModelType      string `binding:"oneof=活动 培训"`
		Name           string `binding:"max=255"`
		Type           string `binding:"max=255"`
		Status         string `binding:"oneof='' 待审核 已驳回 招募中 进行中 已结束"`
		OrganizationId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, req.OrganizationId)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 查询
	var count int64
	var list []activity.Activity

	var tx = bean.MysqlDb.Model(&activity.Activity{})

	tx = tx.Where("`organization_id` in ?", organization_my_ids)

	tx = tx.Where("`model_type`=?", req.ModelType)

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}
	if req.Type != "" {
		tx = tx.Where("`type`=?", req.Type)
	}
	if req.Status != "" {
		tx = tx.Where("`status`=?", req.Status)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func MyOneOrganizationList(c *gin.Context) {

	var req struct {
		Page      int    `binding:"required,gte=1"`
		Limit     int    `binding:"required,gte=1"`
		ModelType string `binding:"oneof=活动 培训"`
		Name      string `binding:"max=255"`
		Type      string `binding:"max=255"`
		Status    string `binding:"oneof='' 待审核 已驳回 招募中 进行中 已结束"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	// 获取登录用户对象
	var adm admin.Admin
	if err := adm.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询
	var count int64
	var list []activity.Activity

	var tx = bean.MysqlDb.Model(&activity.Activity{})

	tx = tx.Where("`organization_id`=?", adm.OrganizationId)

	tx = tx.Where("`model_type`=?", req.ModelType)

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}
	if req.Type != "" {
		tx = tx.Where("`type`=?", req.Type)
	}
	if req.Status != "" {
		tx = tx.Where("`status`=?", req.Status)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func MyDetail(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.Activity
	if err := bean.MysqlDb.Where("id=?", req.ID).Take(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, fmt.Sprintf("数据库错误id:%d", req.ID))
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	c.PureJSON(200, one)
}

func MyEdit(c *gin.Context) {

	var req struct {
		ID                uint   `binding:"max=10000000"`
		ModelType         string `binding:"oneof=活动 培训"`
		OrganizationId    uint   `binding:"max=10000000"`
		Name              string `binding:"max=255"`
		Address           string `binding:"max=512"`
		StartTime         string `binding:"required,datetime=2006-01-02 15:04:05"`
		ServeHour         uint   `binding:"required,max=10000"`
		RecruitmentNumber uint   `binding:"max=10000"`
		ServePeopleNum    uint   `binding:"max=10000"`
		InitiatingUnit    string `binding:"max=255"`

		Type          string `binding:"max=255"`
		ServiceTarget string `binding:"max=255"`

		ResponsibleUserId      uint   `binding:"max=10000000"`
		ResponsiblePerson      string `binding:"max=255"`
		ResponsiblePersonPhone string `binding:"max=255"`
		OtherResponsiblePerson string `binding:"max=255"`

		Content string `binding:"max=2048"`
		// Status  string `binding:"oneof='' 待审核 已驳回 招募中 进行中 已结束"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, req.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", req.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var one activity.Activity
	one.ID = req.ID
	one.OrganizationId = req.OrganizationId
	one.Name = req.Name
	one.Address = req.Address
	one.StartTime = req.StartTime
	// 计算报名截止时间
	StartTime, err := time.ParseInLocation(time.DateTime, req.StartTime, time.Local)
	if err != err {
		var err = fmt.Sprintf("时间解析失败:%s", req.StartTime)
		bean.Log.Error(err)
		c.String(400, err)
		return
	}
	// 报名截止时间为开始时间 前30分钟
	one.RegistrationDeadlineTime = StartTime.Add(time.Minute * -30).Format(time.DateTime)
	// 活动结束时间等于活动开始时间 加上服务时长
	one.EndTime = StartTime.Add(time.Hour * time.Duration(req.ServeHour)).Format(time.DateTime)
	// 计算索引时间
	one.YearMonth = StartTime.Format("2006-01")

	one.ServeHour = req.ServeHour
	one.RecruitmentNumber = req.RecruitmentNumber
	one.ServePeopleNum = req.ServePeopleNum
	one.InitiatingUnit = req.InitiatingUnit

	one.Type = req.Type
	one.ServiceTarget = req.ServiceTarget
	one.ResponsibleUserId = req.ResponsibleUserId
	one.ResponsiblePerson = req.ResponsiblePerson
	one.ResponsiblePersonPhone = req.ResponsiblePersonPhone
	one.OtherResponsiblePerson = req.OtherResponsiblePerson
	one.Content = req.Content

	// 保存对象
	if one.ID == 0 {
		one.ModelType = req.ModelType
		one.ParticipantCount = 0
		one.Status = "待审核"
		if err := bean.MysqlDb.Create(&one).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, "数据库错误")
			return
		}
	} else {

		var one2 activity.Activity
		if err := bean.MysqlDb.Where("id=?", req.ID).First(&one2).Error; err != nil {
			bean.Log.Warning(err)
			c.String(400, fmt.Sprintf("活动不存在id:%d", req.ID))
			return
		}

		if one2.Status != "待审核" && one2.Status != "已驳回" {
			c.String(400, "活动不可修改status："+one2.Status)
			return
		}

		// 状态重置为待审核
		one.Status = "待审核"

		// 修改验证
		if !tools.InList(organization_my_ids, one2.OrganizationId) {
			var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
			bean.Log.Error(err)
			c.String(403, err)
			return
		}

		if err := bean.MysqlDb.Updates(&one).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, "数据库错误")
			return
		}
	}

	c.String(200, "ok")
}

func MyDelete(c *gin.Context) {
	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.Activity
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("活动不存在id:%d", req.ID))
		return
	}

	// org 权限验证
	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	if err := bean.MysqlDb.Delete(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}

// 中心用
func MyCheck(c *gin.Context) {
	var req struct {
		ID     uint   `binding:"max=10000000"`
		Status string `binding:"oneof=已驳回 招募中 已结束"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.Activity
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("活动不存在id:%d", req.ID))
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var two activity.Activity
	two.ID = one.ID
	two.Status = req.Status

	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")

	//消息通知 jldtx
	// 重新获取 updateat 时间
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		// c.String(400, fmt.Sprintf("活动不存在id:%d", req.ID))
		return
	}

	if users, _, err := activity.ActivityFindAdminUser(one); err != nil {
		bean.Log.Error(err)
		// c.String(500, err.Error())
		return
	} else {
		// fmt.Println("通知给申请人:", len(users), "人")
		// fmt.Println("通知给申请人:", org)
		for _, item := range users {
			var Openid = item.Openid
			var page = "pages/index/index"
			var applyProject = one.Name
			var applyTime = one.UpdatedAt
			var applyResult = activity.ActivityStatus(two)
			if err := message_queue.MessageQueueAddT1(Openid, page, applyProject, applyTime, applyResult); err != nil {
				// 错误记录
				bean.Log.Error(err)
			}
		}
	}

}

// 单位用
func MyFinish(c *gin.Context) {
	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.Activity
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("活动不存在id:%d", req.ID))
		return
	}

	if one.Status != "招募中" && one.Status != "进行中" {
		c.String(400, fmt.Sprintf("活动状态为:%s,不可结束", one.Status))
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var two activity.Activity
	two.ID = one.ID
	two.Status = "已结束"

	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}
